package cn.codeforfun.gitee.api.oauth;

import cn.codeforfun.gitee.api.GiteeService;
import cn.codeforfun.gitee.bean.GiteeToken;
import cn.codeforfun.gitee.config.GiteeConfigStorage;
import cn.codeforfun.gitee.utils.JsonUtils;
import cn.codeforfun.gitee.utils.OkHttpUtils;
import lombok.RequiredArgsConstructor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangbin
 */
@RequiredArgsConstructor
public class GiteeOauthServiceImpl implements GiteeOauthService {
    private final GiteeService giteeService;

    @Override
    public GiteeToken getTokenByPassword() throws IOException {
        GiteeConfigStorage giteeConfigStorage = giteeService.getGiteeConfigStorage();

        String oauthPrefix = "https://gitee.com/oauth";
        Map<String, Object> parameterMap = new HashMap<>(6);
        parameterMap.put("username", giteeConfigStorage.getUsername());
        parameterMap.put("password", giteeConfigStorage.getPassword());
        parameterMap.put("client_id", giteeConfigStorage.getClientId());
        parameterMap.put("client_secret", giteeConfigStorage.getClientSecret());
        parameterMap.put("scope", "projects user_info emails enterprises");
        parameterMap.put("grant_type", "password");
        String result = OkHttpUtils.postUrlEncoder(oauthPrefix + "/token", parameterMap);
        return JsonUtils.toBean(result, GiteeToken.class);
    }
}
